<template>
    <div class="job-page communication-page">
        <div class="job-page-center">
            <div class="communication-page-left">
                <el-menu :default-active="activeIndex" mode="horizontal" class="communication-tab"
                         @select="handleSelect">
                    <el-menu-item index="1">顾问沟通</el-menu-item>
                    <el-menu-item index="2">企业沟通</el-menu-item>
                </el-menu>
                <el-scrollbar ref="commScrollbar" style="height: calc(100% - 50px)">
                    <communication-dialog :group="activeIndex" :init-index="leftActive" :comm-list="data"
                                          @on-active="onListItemActive"></communication-dialog>
                </el-scrollbar>
            </div>
            <div class="communication-page-right">
                <div v-if="Number(activeIndex)===2" class="communication-right-head">
                    <div class="communication-tight-title">
                        简历状态：
                        <span>{{activeItem.jrrState}}</span>
                    </div>
                    <div class="communication-tight-title">
                        沟通职位：
                        <span>{{activeItem.jobName}}</span>
                    </div>
                </div>
                <div class="communication-right-content" :class="Number(activeIndex)===2?'content-2':'content-1'">
                    <communication-counselor
                            v-if="leftActive>-1"
                            :counselor="activeItem.counselor"
                            :who="activeIndex"
                            :index-change="leftActive"
                            :len="data.length"
                            :comm-id="activeItem.commId"
                            :to-id="activeItem.toId"
                            :jrr-id="activeItem.jrrId"
                            :decided-q="activeItem.decidedQ"
                            :can-send-q="activeItem.canSendQ"
                    >
                    </communication-counselor>
                    <!--<communication-company v-if="Number(activeIndex)===2"></communication-company>-->
                </div>
            </div>
        </div>
        <el-dialog title="提示" :visible.sync="showChangeQ">
            <change-advisor-dialog :type="1" @click-which="clickDialog"></change-advisor-dialog>
        </el-dialog>
    </div>
</template>

<script>
  import communicationDialog from './communication-dialog'
  import communicationCounselor from './communication-counselor'
  import communicationCompany from './communication-company'
  import _g from '../../assets/utils/global'
  import * as _ from 'underscore'
  import _subject from '../../assets/utils/subject'
  import comm from '../../assets/utils/comm'
  import ChangeAdvisorDialog from './ChangeAdvisorDialog'

  export default {
    data() {
      return {
        showChangeQ: false,
        companyName: null,
        queryId: null,
        wsSub: null,
        companyHeads: [],
        activeIndex: '1',
        data: [],
        leftActive: -1
      }
    },
    components: {
      communicationDialog,
      communicationCounselor,
      communicationCompany,
      ChangeAdvisorDialog
    },
    computed: {
      activeItem() {
        if (this.leftActive === -1) {
          comm.toIcon = null
          //沟通列表为空
          return {
            commId: 0,
            toId: 0,
            jrrId: 0,
            counselor: { name: '', phone: '', time: '' },
            jobName: '',
            jrrState: '',
            decidedQ: false,
            canSendQ: true
          }
        } else {
          comm.toIcon = this.data[this.leftActive].image
          const active = {
            commId: this.data[this.leftActive].commId,
            toId: this.data[this.leftActive].toId,
            jrrId: this.data[this.leftActive].jrrId,
            counselor: this.data[this.leftActive].counselor,
            jobName: this.data[this.leftActive].jobName,
            jrrState: this.data[this.leftActive].jrrState,
            decidedQ: this.data[this.leftActive].decidedQ,
            canSendQ: this.data[this.leftActive].canSendQ
          }
          console.log('active comm', active)
          return active
        }
      }
    },
    methods: {
      scrollTop() {
        //异步滚动
        setTimeout(() => {
          this.$refs['commScrollbar'].wrap.scrollTop = 0
        }, 1)
      },
      insertComm() {
        const params = {
          state: 4,
          platformId: null,
          relationshipId: this.data[this.leftActive].jrrId,
          jobId: this.data[this.leftActive].jobId,
          companyName: '',
          jobName: ''
        }
        _g.apiPost('/talent/clickCommnicationButton.do', params).then(res => {
          console.log('clickCommnicationButton', res)
          if (res && res.status === 0) {
            console.log('start communicate consultant success', params, res)
            this.queryId = res.data
            this.loadList()
          }
        })
      },
      clickDialog(type, which) {
        if (which === 1) {
          this.insertComm()
        }
        this.showChangeQ = false
      },
      getJrrState(state, appropriate) {
        state = Number(state)
        if (state === 2) {
          return '待入职'
        } else if (state === 3) {
          return '入职成功'
        } else if (state === 4) {
          return '不合适'
        } else {
          return '投递成功'
        }
      },
      clearUnread(commId) {
        console.log('clear unread', commId)
        const str = {
          'comid': String(commId),
          'type': 'CLEAR',
          'mainCom': 'talent',
          'mainUserId': String(_subject.getTalentId())
        }
        _subject.ws.next(str)
      },
      newMsg(commId, unread) {
        console.log('index receive new message', commId, unread, this.data)
        let exist = _.find(this.data, t => {
          return t.commId === commId
        })
        if (exist) {
          exist.unread = unread
          exist.last = Date.now()
          if (unread) {
            //现有选中的沟通
            const active = this.data[this.leftActive].commId
            this.data = _.sortBy(this.data, t => {
              return t.last
            })
            this.data.reverse()
            //重新选中
            this.leftActive = _.findIndex(this.data, t => {
              return t.commId === active
            })
          }
        }
      },
      onListItemActive(active) {
        console.log('item change', active)
        //把未读数置为0
        this.clearUnread(this.data[active].commId)
        //赋值
        this.leftActive = active
        //是否改了顾问
        if (!this.data[this.leftActive].canSendQ) {
          this.showChangeQ = true
        }
      },
      handleSelect(val) {
        console.log('platform or company change', val)
        this.activeIndex = val
        this.leftActive = -1
        this.loadList()
      },
      loadList() {
        console.log('start load comm list')
        _g.apiPost('/talent/selectComListByTalentId.do', { state: String(this.activeIndex) })
          .then(res => {
            if (res) {
              console.log('comm list server', res)
              if (res.status === 0) {
                this.data = _.map(res.data, o => {
                  return {
                    jobId: o.jobId,
                    decidedQ: Number(o.appropriate) === 2 || Number(o.appropriate) === 3,
                    unread: o.unreadType === 'talent' ? o.unread : 0,
                    jrrId: o.relationshipId,
                    commId: o.id,
                    toId: o.toId,
                    image: Number(this.activeIndex) === 1 ? o.head : _subject.getCompanyIcon(o.head),
                    name: Number(this.activeIndex) === 1 ? (o.jobName ? o.jobName : '未知') : (o.name ? o.name : '未知'),
                    time: o.lastComtime ? new Date(o.lastComtime).format('MM月dd日') : '未知',
                    last: new Date(o.lastComtime),
                    company: o.companyName,
                    counselor: {
                      name: o.name,
                      phone: o.phone,
                      time: o.workTime
                    },
                    jobName: o.jobName,
                    jrrState: this.getJrrState(o.relationshipState, o.appropriate),
                    canSendQ: Number(o.showList) !== 1
                  }
                })
                console.log('comm list local', this.data)
                //从其他地方调转到顾问沟通界面
                if (this.activeIndex === '1') {
                  if (this.queryId) {
                    let active = _.findIndex(this.data, t => {
                      return t.commId === this.queryId
                    })
                    this.queryId = null
                    if (active > -1) {
                      //指定选中项
                      this.data = _.sortBy(this.data, t => {
                        return t.last
                      })
                      this.data.reverse()
                      this.leftActive = active
                      this.scrollTop()
                    } else {
                      this.data = _.sortBy(this.data, t => {
                        return t.last
                      })
                      this.data.reverse()
                    }
                  }
                } else {
                  //按最后沟通时间倒序排列
                  this.data = _.sortBy(this.data, t => {
                    return t.last
                  })
                  this.data.reverse()
                }
              }
            }
          })
      }
    }
    ,
    created() {
      //订阅服务器的消息
      let self = this
      this.wsSub = _subject.ws.subscribe({
        next(t) {
          if (t.status === 200) {
            let m = t.data.type
            if (m === 'SINGLE_SENDING') {
              let commId = t.data.comid
              let mainId = t.data.mainUserId
              let toId = t.data.toUserId//对方发送的消息
              //通知收到父组件消息
              self.newMsg(Number(commId), Number(t.data.unread))
            }
          }
        }
      })
    }
    ,
    mounted() {
      //点击沟通路由过来的信息
      const commId = this.$route.query.commId
      const companyName = this.$route.query.companyName
      console.log('query params', commId, companyName)
      if (commId) {
        this.companyName = companyName
        this.queryId = commId
        this.activeIndex = '1'
      }
      this.loadList()
    }
    ,
    destroyed() {
      if (this.wsSub) {
        this.wsSub.unsubscribe()
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
